import { TGameStatus, Game } from './class'

const thisInstance: {
  game?: Game
} = { }

export enum EDispatchType { initial, reset, start, pause, goLeft, goRight, fire }
type DispatchPayloadType = {
  [propName:string]: any;
}
type DispatchCommandType = {
  type: EDispatchType;
  payload?: DispatchPayloadType;
}

type GameStateType = { status: TGameStatus; }
export const initialGameReducerState: () => GameStateType = () => ({ status: 'unknown' })
export const reduceHandler: (currentState: GameStateType, command: DispatchCommandType) => GameStateType
= (currentState, command) => {
  switch(command.type) {
    case EDispatchType.initial:
      const {canvasCurrentRef, context} = command.payload || { }
      if (!!canvasCurrentRef || !!context) {
        thisInstance.game = new Game(canvasCurrentRef, context);
        thisInstance.game.initial();
      }
      break;
    case EDispatchType.reset:
      thisInstance.game?.reset();
      break;
    case EDispatchType.start:
      thisInstance.game?.start();
      break;
    case EDispatchType.pause:
      thisInstance.game?.pause();
      break;
    case EDispatchType.goLeft:
      thisInstance.game?.moveAircraft(-5);
      break;
    case EDispatchType.goRight:
      thisInstance.game?.moveAircraft(5);
      break;
    case EDispatchType.fire:
      thisInstance.game?.fire();
      break;
    default:
      return currentState;
  }

  if (!!thisInstance.game?.status) {
    currentState.status = thisInstance.game.status;
  }
  return { ...currentState }
}
